package com.xxd.algo.leetcode.base;

/**
 * @author: XiaoDong.Xie
 * @create: 2020-07-06 14:45
 * @description: 二分查找
 */
public class Question035_SearchInsert {

    public int searchInsert(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }

        return searchInsert(nums, 0, nums.length - 1, target);
    }

    /**
     * 在 l 至 r 上查找target值
     * @param nums
     * @param l
     * @param r
     * @param target
     * @return
     */
    private int searchInsert(int[] nums, int l, int r, int target) {
        int mid = 0;

        while (l < r) {
            mid = l + ((r - l) >> 1);
            if (nums[mid] > target ) {
                r = mid - 1;
            } else if(nums[mid] < target) {
                l = mid + 1;
            } else {
                return mid;
            }
        }

        return nums[l] >= target ? l : l + 1;
    }

    public static void main(String[] args) {
        Question035_SearchInsert searchInsert = new Question035_SearchInsert();
        int[] arr = {1, 3, 4, 5, 6, 7, 8, 9};

        System.out.println(searchInsert.searchInsert(arr, 2));

    }
}
